package br.com.puertorico.mecanismos.ui.converters;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 * Respons&aacute;vel pela remo&ccedil;&atilde;o e insers&atilde;o da
 * m&aacute;scara no valor do CEP.
 *
 * @author <a href="mailto:daniel.camargo@ufms.br">Daniel Camargo</a>
 * @version $id$
 * @see Cep
 */
public class CepConverter implements Converter {

	/**
	 * {@inheritDoc}
	 */
	public Object getAsObject(FacesContext ctx, UIComponent ui, String value) {
		if (value == null || value.trim().length() == 0) {
			return null;
		}
		return value.replaceAll("[^\\d]", "");
	}

	/**
	 * {@inheritDoc}
	 */
	public String getAsString(FacesContext ctx, UIComponent ui, Object value) {
		if (value == null) {
			return null;
		}
		return value.toString().replaceAll("^(\\d{5})(\\d{3})$", "$1-$2");

	}
}